import type { App } from 'vue'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { judementSameArr } from '@/utils/arrayOperation'

/**
 * 用户权限指令
 * @directive 单个权限验证（v-auth="xxx"）
 * @directive 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
 * @directive 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
 */
export function authDirective(app: App) {
  // 单个权限验证（v-auth="xxx"）
  app.directive('auth', {
    mounted(el, binding) {
      const permissionStore = usePermissionStoreWithOut()
      if (permissionStore.getPermissions) {
        const ps = [binding.value].flat().filter((x) => !!x)
        const hasPermissions =
          ps.length < 1 || permissionStore.getPermissions.some((x: any) => ps.includes(x))
        if (!hasPermissions) el.parentNode.removeChild(el)
      }
    }
  })
  // 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
  app.directive('auths', {
    mounted(el, binding) {
      const permissionStore = usePermissionStoreWithOut()
      if (permissionStore.getPermissions) {
        const ps = [binding.value].flat().filter((x) => !!x)
        const hasPermissions =
          ps.length < 1 || permissionStore.getPermissions.some((x: any) => ps.includes(x))
        if (!hasPermissions) el.parentNode.removeChild(el)
      }
    }
  })
  // 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
  app.directive('auth-all', {
    mounted(el, binding) {
      const permissionStore = usePermissionStoreWithOut()
      if (permissionStore.getPermissions) {
        const flag = judementSameArr(binding.value, permissionStore.getPermissions)
        if (!flag) el.parentNode.removeChild(el)
      }
    }
  })
}
